<?php

namespace addons\shopro\service\commission;

use addons\shopro\service\commission\Config;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\commission\AgentUpLog;
use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\commission\Level as LevelModel;
use app\admin\model\shopro\commission\Honor as HonorModel;
use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\shopro\Share as ShareModel;
use app\common\model\stat\ShareMoney as ShareMoneyModel;
use think\Db;
use think\Log;

/**
 * 分销商业务
 */
class Agent
{

    public $user;     // 商城用户
    public $agent;    // 分销商
    public $config;    // 分销设置
    public $parentUserId;
    public $nextAgentTeam;
    public $nextUserTeam;
    private $order;

    /**
     * 构造函数
     *
     * @param mixed $user 用户ID/用户对象
     */
    public function __construct($user)
    {
        if (is_numeric($user)) {
            $this->user = UserModel::get($user);
        } else {
            $this->user = UserModel::get($user->id);
        }
        if (!empty($this->user->id)) {
            $this->agent = AgentModel::with(['level_info', 'honor_info'])->find($this->user->id);
        }

        $this->config = new Config();
    }

    /**
     * 获取分销商实时状态
     */
    public function getAgentStatus($autoCreate = false)
    {
        if (empty($this->agent)) {
            // 自动创建分销商  
            if ($autoCreate) {
                return $this->createNewAgent();
            }
            return NULL;
        }
        return $this->agent->status;
    }

    /**
     * 获取分销商可参与状态 正常和冻结都可正常浏览并统计业绩
     */
    public function isAgentAvaliable()
    {
        $status = $this->getAgentStatus();
        if (in_array($status, [AgentModel::AGENT_STATUS_NORMAL, AgentModel::AGENT_STATUS_FREEZE])) {
            return true;
        }
        return false;
    }

    /**
     * 获取分销商等级
     */
    public function getAgentLevel()
    {
        if (empty($this->agent)) {
            return 0;
        }
        if (empty($this->agent->level_info)) {
            return 1;
        }
        return $this->agent->level_info->level;
    }

    /**
     * 获取分销商奖衔
     */
    public function getAgentHonor()
    {
        if (empty($this->agent)) {
            return 0;
        }
        if (empty($this->agent->honor_info)) {
            return 1;
        }
        return $this->agent->honor_info->honor;
    }

    /**
     * 分销商升级是否锁定
     */
    public function getAgentUpgradeLock()
    {
        if (empty($this->agent)) {
            return true;
        }
        if ($this->agent->upgrade_lock == AgentModel::UPGRADE_LOCK_OPEN) {
            return true;
        }

        return false;
    }

    /**
     * 实时获取上级推荐人
     */
    public function getParentUserId()
    {
        if (empty($this->parentUserId)) {

            $this->parentUserId = 0;

            $parent_user_id = $this->user->parent_user_id;
            // 未直接绑定分销商,从分享记录查找最近的分销商
            if ($parent_user_id === NULL) {
                $shareLog = ShareModel::hasWhere(
                    'agent',
                    function ($query) {
                        return $query->where('status', 'in', [AgentModel::AGENT_STATUS_NORMAL, AgentModel::AGENT_STATUS_FREEZE]);
                    }
                )->where('Share.user_id', $this->user->id)->order('id desc')->find();

                if ($shareLog) {
                    $parent_user_id = $shareLog['share_id'];
                }
            }
            // 再次检查上级分销商是否可用
            if ($parent_user_id > 0) {
                $parentUser = UserModel::where('id', $parent_user_id)->find();
                $parentAgent = AgentModel::avaliable()->where(['user_id' => $parent_user_id])->find();
                if ($parentUser && $parentAgent) {
                    $this->parentUserId = $parentAgent->user_id;
                }
            }
        }

        return $this->parentUserId;
    }

    /**
     * 创建分销商
     */
    public function createNewAgent($event = '', $applyInfo = [])
    {
        // 已经是分销商
        if (!empty($this->agent)) {
            return $this->getAgentStatus();
        }

        $agentStatus = AgentModel::AGENT_STATUS_NULL;

        $condition = $this->config->getBecomeAgentEvent();

        $check = false;  // 是否满足条件
        $needAgentApplyForm = $this->config->isAgentApplyForm();

        if ($event !== '' && $condition['type'] !== $event) {
            return $agentStatus;
        }

        switch ($condition['type']) {
            case 'apply':   // 直接自助申请
                $check = true;
                $needAgentApplyForm = true;
                break;
            case 'goods':   // 需购买指定产品
                $isBuy = \app\admin\model\shopro\order\Order::hasWhere('items', function ($query) use ($condition) {
                    return $query->where('goods_id', 'in', $condition['value'])->where('refund_status', 0);
                })->where('Order.user_id', $this->user->id)->paid()->find();
                if ($isBuy) $check = true;
                break;
            case 'consume': // 消费累计
                if ($this->user->total_consume >= $condition['value']) {
                    $check = true;
                }
                break;
            case 'user': // 新会员注册
                $check = true;
                $needAgentApplyForm = false;
                break;
        }

        // 可以成为分销商 检查系统设置
        if ($check) {
            // 需后台审核
            if ($this->config->isAgentCheck()) {
                $agentStatus = AgentModel::AGENT_STATUS_PENDING;
            } else {
                $agentStatus = AgentModel::AGENT_STATUS_NORMAL;
            }
            // 需要提交资料
            if ($needAgentApplyForm && empty($applyInfo)) {
                $agentStatus = AgentModel::AGENT_STATUS_NEEDINFO;  // 需要主动提交资料,暂时不加分销商信息
            }
        }

        // 可以直接添加分销商信息
        if ($agentStatus === AgentModel::AGENT_STATUS_NORMAL || $agentStatus === AgentModel::AGENT_STATUS_PENDING) {
            AgentModel::create([
                'user_id' => $this->user->id,
                'level' => 1,  // 默认分销商等级
                'status' => $agentStatus,
                'apply_info' => $applyInfo,
                'apply_num' => 1,
                'become_time' => time()
            ]);

            // 绑定上级推荐人
            if ($this->user->parent_user_id === NULL) {
                if ($this->bindUserRelation('agent') && $agentStatus !== AgentModel::AGENT_STATUS_NORMAL) {
                    $this->createAsyncAgentUpgrade($this->user->id);    // 防止真正成为分销商时重新触发升级任务造成冗余
                }
            }
            // 绑定为平台直推
            if ($this->user->parent_user_id === NULL) {
                $this->user->parent_user_id = 0;
                $this->user->save();
            }

            $this->agent = AgentModel::with(['level_info'])->find($this->user->id);

            // 添加分销商状态记录
            LogModel::add($this->user->id, 'agent', ['type' => 'status', 'value' => $agentStatus]);

            // 统计分销层级单链业绩
            if ($agentStatus === AgentModel::AGENT_STATUS_NORMAL) {
                $this->createAsyncAgentUpgrade($this->user->id);
            }
        }
        return $agentStatus;
    }

    /**
     * 绑定用户关系
     *
     * @param string $event 事件标识(share=点击分享链接, pay=首次支付, agent=成为子分销商)
     * @param int $bindAgentId 可指定需绑定的分销商用户ID 默认从分享记录中去查
     */
    public function bindUserRelation($event, $bindAgentId = NULL)
    {
        $bindCheck = false;   // 默认不绑定

        // 该用户已经有上级
        if ($this->user->parent_user_id !== NULL) {
            return false;
        }

        // 不满足绑定下级事件
        if ($this->config->getInviteLockEvent() !== $event) {
            return false;
        }

        switch ($this->config->getInviteLockEvent()) {
            case 'share':
                $bindCheck = true;
                break;
            case 'pay':
                if ($this->user->total_consume > 0) {
                    $bindCheck = true;
                }
                break;
            case 'agent':
                $bindCheck = true;
                break;
        }

        if (!$bindCheck) {
            return false;
        }

        if ($bindAgentId === NULL) {
            $bindAgentId = $this->getParentUserId();
        }

        if (!$bindAgentId) {
            return false;
        }

        $bindAgent = new Agent($bindAgentId);

        if (!$bindAgent->isAgentAvaliable()) {
            return false;
        }

        // 允许绑定用户
        $this->user->parent_user_id = $bindAgent->user->id;
        $this->user->parent_user_time = time();
        $this->user->save();

        // 添加推广记录
        LogModel::add($bindAgent->user->id, 'share', ['user' => $this->user]);
        return true;
    }


    /**
     * 创建[分销商升级&统计业绩]异步队列任务
     * 为了防止计算量大而引起阻塞,使用异步递归
     */
    public function createAsyncAgentUpgrade($user_id = 0, $order_id = 0)
    {
        if ($user_id === 0) {
            $user_id = $this->user->id;
        }
        \think\Queue::push('\addons\shopro\job\Commission@agentUpgrade', [
            'user_id' => $user_id,
            'order_id' => $order_id
        ], 'shopro');

        //分销商奖衔升级也在这里
        \think\Queue::push('\addons\shopro\job\Commission@agentUpgradeHonor', [
            'user_id' => $user_id
        ], 'shopro');
    }

//    /**
//     * 创建[分销商升级奖衔]异步队列任务
//     * 为了防止计算量大而引起阻塞,使用异步递归
//     */
//    public function createAsyncAgentUpgradeHonor($user_id = 0)
//    {
//        if ($user_id === 0) {
//            $user_id = $this->user->id;
//        }
//        \think\Queue::push('\addons\shopro\job\Commission@agentUpgradeHonor', [
//            'user_id' => $user_id
//        ], 'shopro');
//    }

//    /**
//     * 创建[金牌会员当日分红]异步队列任务
//     * 为了防止计算量大而引起阻塞,使用异步递归
//     */
//    public function createAsyncAgentLevel5SharMoney($user_id = 0)
//    {
//        \think\Queue::push('\addons\shopro\job\Commission@runAgentLevel5SharMoney', [], 'shopro');
//    }

    /**
     * 执行用户奖衔升级
     * */
    public function runAgentUpgradeHonor($user_id = 0, $orderId = 0)
    {
        if ($this->isAgentAvaliable()) {

            // 分销商自动升级
            if (!$this->getAgentUpgradeLock()) {
                $canUpgradeHonor = $this->checkAgentUpgradeLHonor();
                if ($canUpgradeHonor) {
                    $this->agent->honor = $canUpgradeHonor;
                    LogModel::add($this->user->id, 'agent', ['type' => 'honor', 'honor' => HonorModel::find($canUpgradeHonor)]);
                    //奖衔升级记录
                    AgentUpLog::upgradeUserUpLog($this->agent->user->id, $this->agent->honor, $canUpgradeHonor);
                    $this->agent->save();
                }
            }
            \think\Log::info('奖衔升级 [ID=' . $this->user->id . '&nickname=' . $this->user->nickname . '] ---Ended');
        }
    }

    /**
     * 金牌会员分红
     * 将当前商城中当日销售额的4%纳入分红池，平均分配给当日达标的所有金牌会员
     * 1月1日，当前商城截止24:00销售总额为150000元，其中当日升级为金牌会员的10人，则150000元×4%=6000元纳入分红池，均分后6000元÷10人=每人可得600元。
     * */
    public function runAgentLevel5SharMoney()
    {
        // 获取昨日的起始和结束时间戳
        $yesterday = getYesterdayDate('int');

        // 计算昨日的总销售额（只统计已支付订单）
        $yesterdayPayFee = Order::where('status', 'paid')
            ->whereBetween('paid_time', [$yesterday['start'], $yesterday['end']])
            ->sum('pay_fee');

        // 获取昨日升级为金牌会员（level = 5）的用户ID列表
        $goldMemberUserIds = AgentUpLog::getUserIdsUpToLevel5($yesterday['start'], $yesterday['end']);

        // 如果没有符合条件的用户，则记录日志并退出
        if (empty($goldMemberUserIds)) {
            ShareMoneyModel::create([
                'date' => date('Ymd', $yesterday['start']),
                'real_pay_money' => 0,
                'share_rate' => '4%',
                'share_user_count' => 0,
                'share_money' => 0,
                'remark' => '金牌会员当日分红',
                'content' => json_encode([], JSON_UNESCAPED_UNICODE),
                'createtime' => time(),
                'updatetime' => time()
            ]);
            \think\Log::info('金牌会员分红：昨日无升级为金牌会员的用户。');
            return;
        }

        // 计算分红池金额（销售额的4%），并保留两位小数
        $bonusPool = round($yesterdayPayFee * 0.04, 2);
        // 计算每个金牌会员可分得的金额，保留两位小数
        $bonusPerUser = round($bonusPool / count($goldMemberUserIds), 2);

        // 遍历所有金牌会员，通过事务执行充值操作
        foreach ($goldMemberUserIds as $userId) {
            $result = Db::transaction(function () use ($userId, $bonusPerUser) {
                // 这里构造参数数组也可以直接传入变量
                return WalletService::change($userId, 'money', $bonusPerUser, 'admin_recharge', [], '金牌会员当日分红');
            });
            if (!$result) {
                \think\Log::error("金牌会员分红充值失败：user_id={$userId}, bonus={$bonusPerUser}");
            }
        }

        $user_list = UserModel::whereIn('id', $goldMemberUserIds)->field('id,nickname')->select();
        $content = [];
        foreach ($user_list as $user) {
            $content[] = ['user_id' => $user['id'], 'nickname' => $user['nickname'], 'bonusPerUser' => $bonusPerUser];
        }

        ShareMoneyModel::create([
            'date' => date('Ymd', $yesterday['start']),
            'real_pay_money' => $yesterdayPayFee,
            'share_rate' => '4%',
            'share_user_count' => count($goldMemberUserIds),
            'share_money' => $bonusPool,
            'remark' => '金牌会员当日分红',
            'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
            'createtime' => time(),
            'updatetime' => time()
        ]);
        // 记录操作日志
        \think\Log::info("金牌会员分红：共发放分红金额{$bonusPool}元，每人获得{$bonusPerUser}元，用户ID：" . implode(',', $goldMemberUserIds));
    }

    /**
     * 销售业绩提成
     * 以经理2万，总监20万，董事50万，发展委100万以上的直推达标前提，用自己当月直推的下级团队全部人员的销售订单总和，按经理3%，总监3%，董事3%，发展委2%比例，平均分给当前团队同级别的所有人。
     * */
    public function runMonthSharMoney()
    {
        // 1. 获取上月的起始和结束时间戳
        $lastMonth = getLastMonthDate('int');

        // 2. 统计上月总销售额（只统计已支付订单）
        $monthlySales = Order::where('status', 'paid')
            ->whereBetween('paid_time', [$lastMonth['start'], $lastMonth['end']])
            ->sum('pay_fee');

        if ($monthlySales <= 0) {
            \think\Log::info('[销售业绩提成] 上月销售额为 0，无需发放。');
            return;
        }

        // 3. 获取所有 honor > 1 的用户及其提成比例
        //    假设 honorInfo 中有 xiaoshou_ticheng 字段，表示提成百分比
        $agentHonorUsers = AgentModel::where('honor', '>', 1)
            ->with(['honorInfo'])
            ->field('user_id,honor')
            ->select();

        if (!$agentHonorUsers) {
            \think\Log::info('[销售业绩提成] 上月无任何有头衔的用户，无需分配。');
            return;
        }

        // 4. 整理用户数据，按 honor 分组
        $groupedByHonor = [];
        foreach ($agentHonorUsers as $user) {
            // 确保提成比例是浮点数
            $rate = isset($user->honorInfo->xiaoshou_ticheng)
                ? (float)$user->honorInfo->xiaoshou_ticheng
                : 0;

            $groupedByHonor[$user->honor][] = [
                'user_id' => $user->user_id,
                'xiaoshou_ticheng' => $rate,
            ];
        }

        // 5. 逐个 honor 头衔发放提成
        //    同一 honor 的用户提成比例相同，
        foreach ($groupedByHonor as $honor => $userList) {
            if (empty($userList)) {
                continue;
            }

            // 取第一个用户的提成比例，假设同一 honor 下所有人相同
            $commissionRate = $userList[0]['xiaoshou_ticheng'];
            if ($commissionRate <= 0) {
                Log::info("Honor={$honor} 提成比例为 0，跳过。");
                continue;
            }
            // 计算提成池
            // e.g. 如果 xiaoshou_ticheng=3 => 3%，则 monthlySales * (3 / 100)
            $bonusPool = round($monthlySales * ($commissionRate / 100), 2);

            $count = count($userList);
            // 如果同头衔人数>0，计算人均
            $bonusPerUser = $count > 0 ? round($bonusPool / $count, 2) : 0;

            // 无需分发时直接跳过
            if ($bonusPerUser <= 0) {
                \think\Log::info("Honor={$honor} 提成池={$bonusPool} 人数={$count} 人均={$bonusPerUser}，跳过。");
                continue;
            }

            // 6. 遍历用户发放，每人 bonusPerUser
            //    单个用户单个事务，避免部分失败导致整体回滚
            foreach ($userList as $info) {
                $uid = $info['user_id'];
                try {
                    Db::transaction(function () use ($uid, $bonusPerUser) {
                        WalletService::change(
                            $uid,
                            'money',
                            $bonusPerUser,
                            'admin_recharge',
                            [],
                            '销售业绩提成'
                        );
                    });
                } catch (\Exception $e) {
                    \think\Log::error("[销售业绩提成] 发放失败: user_id={$uid}, bonus={$bonusPerUser}, error=" . $e->getMessage());
                }
            }

            // 记录日志
            \think\Log::info("[销售业绩提成] Honor={$honor}, 提成比例={$commissionRate}%, 总额={$bonusPool}, 人数={$count}, 人均={$bonusPerUser}");
        }
    }

    /**
     * 执行用户统计、分销商信息统计、分销商等级升级计划 (递归往上升级)
     *
     * @param bool $upgrade 执行分销商等级升级
     */
    public function runAgentUpgradePlan($upgrade = true, $orderId = 0)
    {
        if ($this->isAgentAvaliable()) {
            if ($orderId) {
                // 这里可以直接接$order
                // 重新获取订单
                $this->order = Order::with('items')->where('id', $orderId)->find();

                $month = date('Ym');
                $this->agent->child_order_month = AgentModel::setChildOrderMonth($month, $this->order->pay_fee);
            }

            // 获取下级直推团队用户信息
            $nextUserTeam = $this->getNextUserTeam();

            $nextAgentTeam = $this->getNextAgentTeam();

            // 一级用户人数
            $this->agent->child_user_count_1 = count($nextUserTeam);

            // 二级用户人数 = 一级分销商的一级用户人数
            $this->agent->child_user_count_2 = array_sum(array_column($nextAgentTeam, 'child_user_count_1'));

            // 团队用户人数 = 一级用户人数 + 一级用户的团队用户人数
            $this->agent->child_user_count_all = $this->agent->child_user_count_1 + array_sum(array_column($nextAgentTeam, 'child_user_count_all'));

            // 一级分销商人数
            $this->agent->child_agent_count_1 = count($nextAgentTeam);

            // 二级分销商人数 = 一级分销商的一级分销商人数
            $this->agent->child_agent_count_2 = array_sum(array_column($nextAgentTeam, 'child_agent_count_1'));

            // 团队分销商人数 = 一级分销商人数 + 一级分销商的团队分销商人数
            $this->agent->child_agent_count_all = $this->agent->child_agent_count_1 + array_sum(array_column($nextAgentTeam, 'child_agent_count_all'));

            // 二级分销订单金额 = 一级分销商的一级分销订单金额 + 一级分销商的自购订单金额
            $this->agent->child_order_money_2 = array_sum(array_column($nextAgentTeam, 'child_order_money_1')) + array_sum(array_column($nextAgentTeam, 'child_order_money_0'));

            // 团队分销订单金额 = 自购分销订单金额 + 一级分销订单金额 + 一级所有分销商的团队分销订单总金额
            $this->agent->child_order_money_all = $this->agent->child_order_money_0 + $this->agent->child_order_money_1 + array_sum(array_column($nextAgentTeam, 'child_order_money_all'));

            // 二级分销订单数量 = 一级分销商的一级分销订单数量 + 一级分销商的自购订单数量
            $this->agent->child_order_count_2 = array_sum(array_column($nextAgentTeam, 'child_order_count_1')) + array_sum(array_column($nextAgentTeam, 'child_order_count_0'));

            // 团队分销订单数量 = 自购分销订单数量 + 一级分销订单数量 + 一级所有分销商的团队分销订单总数量
            $this->agent->child_order_count_all = $this->agent->child_order_count_0 + $this->agent->child_order_count_1 + array_sum(array_column($nextAgentTeam, 'child_order_count_all'));

            // 一级分销商等级统计
            $child_agent_level_1 = array_count_values(array_column($nextAgentTeam, 'level'));
            ksort($child_agent_level_1);
            $this->agent->child_agent_level_1 = $child_agent_level_1;

            // 团队分销商等级统计 = 一级分销商等级 + 一级分销商的团队分销商等级
            $child_agent_level_all = $this->childAgentLevelCount(array_column($nextAgentTeam, 'child_agent_level_all'), $this->agent->child_agent_level_1);
            ksort($child_agent_level_all);
            $this->agent->child_agent_level_all = $child_agent_level_all;

            // 一级分销商奖衔统计
            $child_agent_honor_1 = array_count_values(array_column($nextAgentTeam, 'honor'));
            ksort($child_agent_honor_1);
            $this->agent->child_agent_honor_1 = $child_agent_honor_1;

            // 团队分销商奖衔统计 = 一级分销商奖衔 + 一级分销商的团队分销商奖衔
            $child_agent_honor_all = $this->childAgentHonorCount(array_column($nextAgentTeam, 'child_agent_honor_all'), $this->agent->child_agent_honor_1);
            ksort($child_agent_honor_all);
            $this->agent->child_agent_honor_all = $child_agent_honor_all;

            $this->agent->save();

            // 分销商自动升级
            if (!$this->getAgentUpgradeLock() && $upgrade) {
                $canUpgradeLevel = $this->checkAgentUpgradeLevel();
                if ($canUpgradeLevel) {
                    if ($this->config->isUpgradeCheck()) {
                        $this->agent->level_status = $canUpgradeLevel;
                    } else {
                        $this->agent->level = $canUpgradeLevel;
                        LogModel::add($this->user->id, 'agent', ['type' => 'level', 'level' => LevelModel::find($canUpgradeLevel)]);
                    }
                    $this->agent->save();
                    //升级记录
                    AgentUpLog::upgradeUserUpLog($this->agent->user->id, $canUpgradeLevel, $this->agent->honor);
                }
            }
            \think\Log::info('统计分销商业绩[ID=' . $this->user->id . '&nickname=' . $this->user->nickname . '] ---Ended');
        }

        $parentUserId = $this->getParentUserId();
        if ($parentUserId) {
            $this->createAsyncAgentUpgrade($parentUserId);
        }
    }

    /**
     * 统计团队分销商等级排布
     */
    private function childAgentLevelCount($childAgentLevelArray, $childAgentLevel1Array)
    {
        $childAgentLevelCount = [];
        foreach ($childAgentLevelArray as &$agentLevel) {
            if (!empty($agentLevel)) {
                $agentLevel = json_decode($agentLevel, true);
                array_walk($agentLevel, function ($count, $level) use (&$childAgentLevelCount) {
                    if (isset($childAgentLevelCount[$level])) {
                        $childAgentLevelCount[$level] += $count;
                    } else {
                        $childAgentLevelCount[$level] = $count;
                    }
                });
            }
        }
        array_walk($childAgentLevel1Array, function ($count, $level) use (&$childAgentLevelCount) {
            if (isset($childAgentLevelCount[$level])) {
                $childAgentLevelCount[$level] += $count;
            } else {
                $childAgentLevelCount[$level] = $count;
            }
        });
        return $childAgentLevelCount;
    }

    /**
     * 统计团队分销商奖衔排布
     */
    private function childAgentHonorCount($childAgentLevelArray, $childAgentLevel1Array)
    {
        $childAgentLevelCount = [];
        foreach ($childAgentLevelArray as &$agentLevel) {
            if (!empty($agentLevel)) {
                $agentLevel = json_decode($agentLevel, true);
                array_walk($agentLevel, function ($count, $honor) use (&$childAgentLevelCount) {
                    if (isset($childAgentLevelCount[$honor])) {
                        $childAgentLevelCount[$honor] += $count;
                    } else {
                        $childAgentLevelCount[$honor] = $count;
                    }
                });
            }
        }
        array_walk($childAgentLevel1Array, function ($count, $honor) use (&$childAgentLevelCount) {
            if (isset($childAgentLevelCount[$honor])) {
                $childAgentLevelCount[$honor] += $count;
            } else {
                $childAgentLevelCount[$honor] = $count;
            }
        });
        return $childAgentLevelCount;
    }

    /**
     * 获取下级分销商团队
     */
    public function getNextAgentTeam()
    {
        if (!$this->isAgentAvaliable()) {
            return [];
        }
        if (empty($this->nextAgentTeam)) {
            $this->nextAgentTeam = AgentModel::hasWhere('user', function ($query) {
                return $query->where('parent_user_id', $this->user->id);
            })->column('user_id, Agent.level, child_user_count_1, child_user_count_all,child_agent_count_1, child_agent_count_all, child_order_money_0, child_order_money_1, child_order_money_all, child_order_count_0, child_order_count_1, child_order_count_all, child_agent_level_1, child_agent_level_all,child_agent_honor_1,child_agent_honor_all,child_order_month');
        }
        return $this->nextAgentTeam;
    }

    /**
     * 获取下级直推团队用户
     */
    public function getNextUserTeam()
    {
        if (!$this->isAgentAvaliable()) {
            return [];
        }
        if (empty($this->nextUserTeam)) {
            $this->nextUserTeam = UserModel::where(['parent_user_id' => $this->user->id, 'status' => 'normal'])->column('id');
        }
        return $this->nextUserTeam;
    }

    /**
     * 获取可升级的分销商等级
     */
    private function getNextAgentLevel()
    {
        $nextAgentLevel = [];
        $agentLevel = $this->getAgentLevel();
        if ($agentLevel) {
            $nextAgentLevel = LevelModel::where('level', '>', $agentLevel)->order('level asc')->select();
        }
        return $nextAgentLevel;
    }

    /**
     * 获取当前的分销商等级
     */
    public function getNowAgentLevel()
    {
        $nextAgentLevel = [];
        $agentLevel = $this->getAgentLevel();
        if ($agentLevel) {
            $nextAgentLevel = LevelModel::where('level', '=', $agentLevel)->order('level asc')->find();
        }
        return $nextAgentLevel;
    }

    /**
     *
     * 获取可升级的分销商奖衔
     */
    private function getNextAgentHonor()
    {
        $nextAgentHonor = [];
        $agentHonor = $this->getAgentHonor();
        if ($agentHonor) {
            $nextAgentHonor = HonorModel::where('honor', '>', $agentHonor)->order('honor asc')->select();
        }
        return $nextAgentHonor;
    }

    /**
     * 比对当前分销商条件是否满足升级规则
     */
    private function checkAgentUpgradeLevel()
    {
        $nextAgentLevel = $this->getNextAgentLevel();
Log::info('==========================');
        if (count($nextAgentLevel)) {
            foreach ($nextAgentLevel as $level) {
                $checkLevel[$level->level] = $this->isMatchUpgradeLevelRule($level);
                // 不允许越级升级
                if (!$this->config->isUpgradeJump()) break;
            }
            $checkLevel = array_reverse($checkLevel, true);
            $canUpgradeLevel = array_search(true, $checkLevel);
            if ($canUpgradeLevel) {
                return $canUpgradeLevel;
            }
        }
        return 0;
    }

    /**
     * 比对当前分销商条件是否满足升头衔规则
     */
    private function checkAgentUpgradeLHonor()
    {

        $nextAgentHonor = $this->getNextAgentHonor();

        if (count($nextAgentHonor)) {
            foreach ($nextAgentHonor as $honor) {
                $checkHonor[$honor->honor] = $this->isMatchUpgradeHonorRule($honor);
                // 不允许越级升级
                if (!$this->config->isUpgradeJump()) break;
            }
            $checkHonor = array_reverse($checkHonor, true);
            $canUpgradeHonor = array_search(true, $checkHonor);
            if ($canUpgradeHonor) {
                return $canUpgradeHonor;
            }
        }
        return 0;
    }

    /**
     * 分销商升级规则检查
     */
    public function isMatchUpgradeLevelRule($level)
    {
        foreach ($level->upgrade_rules as $name => $value) {
            $match[$name] = false;
            switch ($name) {
                case 'total_consume':   // 用户消费金额
                    $match[$name] = $this->user->$name >= $value;
                    break;
                case 'single_consume':   // 用户消费金额
                    if (empty($this->order)) {
                        break;
                    }

                    //当前是会员,订单是补差价金额,需要再下单页面限制
                    $nowLevel_single_consume = 0;
                    Log::info("用户金额$nowLevel_single_consume");
                    if ($this->agent->level > 1) {

                        $uniqueGoodsIds = array_unique(array_column(objectToArray($this->order->items), 'goods_id'));
                        $goodsTypes = Goods::whereIn('id',$uniqueGoodsIds)->column('goods_type');

                        foreach ($goodsTypes as $goods_type) {
                            Log::info("商品类型{$goods_type}");

                            if ($goods_type === 'bucha') {
                                $now_level = $this->getNowAgentLevel();
                                Log::info("用户当前等级金额{$now_level['upgrade_rules']['single_consume']}");
                                $nowLevel_single_consume = !empty($now_level['upgrade_rules']['single_consume']) ? $now_level['upgrade_rules']['single_consume'] : 0;
                            }
                        }
                    }
                    Log::info("用户计算后的金额$nowLevel_single_consume");

                    $pay_fee = (float)$this->order->pay_fee + (float)$nowLevel_single_consume;
                    $value = (float)$value;
                    $match[$name] = $pay_fee >= $value;
                    Log::info("升级当钱金额$pay_fee");

                    break;
                case 'child_user_count_all':    // 团队用户人数
                case 'child_user_count_1':  // 一级用户人数
                case 'child_user_count_2':  // 二级用户人数
                case 'child_order_money_0': // 自购分销订单金额
                case 'child_order_money_1': // 一级分销订单金额
                case 'child_order_money_2': // 二级分销订单金额
                case 'child_order_money_all': // 团队分销订单金额

                case 'child_order_count_0': // 自购分销订单数量
                case 'child_order_count_1': // 一级分销订单数量
                case 'child_order_count_2': // 二级分销订单数量
                case 'child_order_count_all': // 团队分销订单数量

                case 'child_agent_count_1': // 一级分销商人数
                case 'child_agent_count_2': // 二级分销商人数
                case 'child_agent_count_all': // 团队分销商人数
                    $match[$name] = $this->agent->$name >= $value;
                    break;

                case 'child_agent_level_1': // 一级分销商等级统计
                case 'child_agent_level_all':   // 团队分销商等级统计
                    $match[$name] = true;
                    if (count($value) > 0) {
                        if (empty($this->agent->$name)) {
                            $match[$name] = false;
                        } else {
                            foreach ($value as $k => $row) {
                                if (!isset(($this->agent->$name)[$row['level']]) || ($this->agent->$name)[$row['level']] < $row['count']) {
                                    $match[$name] = false;
                                    break;
                                }
                            }
                        }
                    }
                    break;
                case 'child_agent_honor_1': // 一级分销商奖衔统计
                case 'child_agent_honor_all':   // 团队分销商奖衔统计
                    $match[$name] = true;
                    if (count($value) > 0) {
                        if (empty($this->agent->$name)) {
                            $match[$name] = false;
                        } else {
                            foreach ($value as $k => $row) {
                                if (!isset(($this->agent->$name)[$row['honor']]) || ($this->agent->$name)[$row['honor']] < $row['count']) {
                                    $match[$name] = false;
                                    break;
                                }
                            }
                        }
                    }
                    break;
            }

            // ①满足任意一种条件:只要有一种符合立即返回可以升级状态
            if (!$level->upgrade_type && $match[$name]) {
                return true;
                break;
            }

            // ②满足所有条件:不满足任意一种条件立即返回不可升级状态
            if ($level->upgrade_type && !$match[$name]) {
                return false;
                break;
            }
        }

        // 循环完所有的 如果是①的情况则代表都不符合条件，如果是②则代表都符合条件 返回对应状态即可
        return boolval($level->upgrade_type);
    }

    /**
     * 分销商升级奖衔规则检查
     */
    public function isMatchUpgradeHonorRule($honor)
    {
//        echo '<pre>';
//        var_dump(objectToArray($honor));die();
        foreach ($honor->upgrade_rules as $name => $value) {
            $match[$name] = false;
            switch ($name) {
                case 'total_consume':   // 用户消费金额
                    $match[$name] = $this->user->$name >= $value;
                    break;
                case 'level':   // 用户等级大于指定等级
                    $match[$name] = $this->agent->level >= $value;
                    break;
                case 'single_consume':   // 用户单笔订单消费金额
                    if (empty($this->order)) {
                        break;
                    }
                    $pay_fee = (float)$this->order->pay_fee;
                    $value = (float)$value;
                    $match[$name] = $pay_fee >= $value;
                    break;
                case 'child_user_count_all':    // 团队用户人数
                case 'child_user_count_1':  // 一级用户人数
                case 'child_user_count_2':  // 二级用户人数
                case 'child_order_money_0': // 自购分销订单金额
                case 'child_order_money_1': // 一级分销订单金额
                case 'child_order_money_2': // 二级分销订单金额
                case 'child_order_money_all': // 团队分销订单金额

                case 'child_order_count_0': // 自购分销订单数量
                case 'child_order_count_1': // 一级分销订单数量
                case 'child_order_count_2': // 二级分销订单数量
                case 'child_order_count_all': // 团队分销订单数量

                case 'child_agent_count_1': // 一级分销商人数
                case 'child_agent_count_2': // 二级分销商人数
                case 'child_agent_count_all': // 团队分销商人数
                    $match[$name] = $this->agent->$name >= $value;
                    break;

                case 'child_agent_level_1': // 一级分销商等级统计
                case 'child_agent_level_all':   // 团队分销商等级统计
                    $match[$name] = true;
                    if (count($value) > 0) {
                        if (empty($this->agent->$name)) {
                            $match[$name] = false;
                        } else {
                            foreach ($value as $k => $row) {
                                if (!isset(($this->agent->$name)[$row['level']]) || ($this->agent->$name)[$row['level']] < $row['count']) {
                                    $match[$name] = false;
                                    break;
                                }
                            }
                        }
                    }
                    break;
                case 'child_agent_honor_1': // 一级分销商奖衔统计
                case 'child_agent_honor_all':   // 团队分销商奖衔统计
                    $match[$name] = true;
                    if (count($value) > 0) {
                        if (empty($this->agent->$name)) {
                            $match[$name] = false;
                        } else {
                            foreach ($value as $k => $row) {
                                if (!isset(($this->agent->$name)[$row['honor']]) || ($this->agent->$name)[$row['honor']] < $row['count']) {
                                    $match[$name] = false;
                                    break;
                                }
                            }
                        }
                    }
                    break;
                case 'child_order_month':   // 团队分销商订单统计
                    $nextAgentTeam = $this->getNextAgentTeam();
                    $nextChildOrderMonth = array_column($nextAgentTeam, 'child_order_month');

                    // 1. 过滤 NULL 值
                    $nextChildOrderMonth = array_filter($nextChildOrderMonth, function ($item) {
                        return !is_null($item) && !empty($item);
                    });
                    // 2. 解析 JSON 数据
                    $parsedData = array_map(function ($json) {
                        return json_decode($json, true);
                    }, $nextChildOrderMonth);
                    // 3. 获取上个月的 YYYYMM 格式
                    $lastMonth = date('Ym', strtotime('-1 month'));
                    // 4. 提取上个月的数据（可能有多个来源）
                    $lastMonthData = [];
                    foreach ($parsedData as $data) {
                        if (isset($data[$lastMonth])) {
                            $lastMonthData[] = $data[$lastMonth]; // **收集多个数据**
                        }
                    }
                    // 5. 处理匹配逻辑
                    $match[$name] = false;
                    if (empty($lastMonthData)) {
                        break;
                    }
                    // 6. 计算 `money` 总额
                    $totalMoney = array_sum(array_column($lastMonthData, 'money'));
                    // 7. 判断是否符合要求
                    $match[$name] = $totalMoney >= $value;
                    break;

            }

            // ①满足任意一种条件:只要有一种符合立即返回可以升级状态
            if (!$honor->upgrade_type && $match[$name]) {
                return true;
                break;
            }

            // ②满足所有条件:不满足任意一种条件立即返回不可升级状态
            if ($honor->upgrade_type && !$match[$name]) {
                return false;
                break;
            }
        }

        // 循环完所有的 如果是①的情况则代表都不符合条件，如果是②则代表都符合条件 返回对应状态即可
        return boolval($honor->upgrade_type);
    }

}
